<?php
    class ApiCenter_ProductApi_IndexController extends Mage_Core_Controller_Front_Action{
       
        public function ppAction() {
            //Basic parameters that need to be provided for oAuth authentication
            //on Magento
            $params = array(
                'siteUrl' => 'http://47.88.2.1/oauth',
                'requestTokenUrl' => 'http://47.88.2.1/oauth/initiate',
                'accessTokenUrl' => 'http://47.88.2.1/oauth/token',
                'authorizeUrl' => 'http://47.88.2.1/admin/oAuth_authorize',//This URL is used only if we authenticate as Admin user type
                'consumerKey' => '1dcd7b1850155e0f5d864ac985beb347',//Consumer key registered in server administration
                'consumerSecret' => 'eb58708cbb91e7ce779986fe970a76a3',//Consumer secret registered in server administration
                'callbackUrl' => 'http://47.88.2.1/restconnect/index/callback',//Url of callback action below
            );
            $oAuthClient = Mage::getModel('restconnect/oauth_client');
            $oAuthClient->reset();
            $oAuthClient->init($params);
            $oAuthClient->authenticate();
            return;
        }
        public function callbackAction() {
            $oAuthClient = Mage::getModel('restconnect/oauth_client');
            $params = $oAuthClient->getConfigFromSession();
            $oAuthClient->init($params);
            $state = $oAuthClient->authenticate();
            if ($state == Vfeelit_RestConnect_Model_OAuth_Client::OAUTH_STATE_ACCESS_TOKEN) {
                $acessToken = $oAuthClient->getAuthorizedToken();
            }
            $restClient = $acessToken->getHttpClient($params);
            // Set REST resource URL
            $restClient->setUri('http://learn.magento.com/api/rest/products');
            // In Magento it is neccesary to set json or xml headers in order to work
            $restClient->setHeaders('Accept', 'application/json');
            // Get method
            $restClient->setMethod(Zend_Http_Client::GET);
            //Make REST request
            $response = $restClient->request();
            // Here we can see that response body contains json list of products
            Zend_Debug::dump($response);
            return;
        }
        
        
        
        
        
        
        
        
        
        /**
         *  查询属性的选项值
         **/
        public function testAction(){

            //key: 1dcd7b1850155e0f5d864ac985beb347
            //secret: eb58708cbb91e7ce779986fe970a76a3
            
            $callbackUrl = "http://localhost/rest_api.php";
            $temporaryCredentialsRequestUrl = "http://47.88.2.1/oauth/initiate?oauth_callback=" . urlencode($callbackUrl);
            $adminAuthorizationUrl = 'http://47.88.2.1/oauth/authorize';
            $accessTokenRequestUrl = 'http://47.88.2.1/oauth/token';
            $apiUrl = 'http://47.88.2.1/api/rest';
            $consumerKey = '1dcd7b1850155e0f5d864ac985beb347';
            $consumerSecret = 'eb58708cbb91e7ce779986fe970a76a3';
            
            session_start();
            if (!isset($_GET['oauth_token']) && isset($_SESSION['state']) && $_SESSION['state'] == 1) {
                $_SESSION['state'] = 0;
            }
            try {
                $authType = ($_SESSION['state'] == 2) ? OAUTH_AUTH_TYPE_AUTHORIZATION : OAUTH_AUTH_TYPE_URI;
                $oauthClient = new OAuth($consumerKey, $consumerSecret, OAUTH_SIG_METHOD_HMACSHA1, $authType);
                $oauthClient->enableDebug();
            
                if (!isset($_GET['oauth_token']) && !$_SESSION['state']) {
                    $requestToken = $oauthClient->getRequestToken($temporaryCredentialsRequestUrl);
                    $_SESSION['secret'] = $requestToken['oauth_token_secret'];
                    $_SESSION['state'] = 1;
                    header('Location: ' . $adminAuthorizationUrl . '?oauth_token=' . $requestToken['oauth_token']);
                    exit;
                } else if ($_SESSION['state'] == 1) {
                    $oauthClient->setToken($_GET['oauth_token'], $_SESSION['secret']);
                    $accessToken = $oauthClient->getAccessToken($accessTokenRequestUrl);
                    $_SESSION['state'] = 2;
                    $_SESSION['token'] = $accessToken['oauth_token'];
                    $_SESSION['secret'] = $accessToken['oauth_token_secret'];
                    header('Location: ' . $callbackUrl);
                    exit;
                } else {
                    $oauthClient->setToken($_SESSION['token'], $_SESSION['secret']);
                    $resourceUrl = "$apiUrl/products";
                    $oauthClient->fetch($resourceUrl);
                    $productsList = json_decode($oauthClient->getLastResponse());
                    print_r($productsList);
                }
            } catch (OAuthException $e) {
                print_r($e);
            }
              
        }
        public function opAction(){
            $encryptedData="HR+cPs5zKrEmsgTaJSV6SBO/LImAnhabv6g02zHodcumjMovnpMQDmSBPIdA9LYT8LkNoTZfVEXk YlDozaOTwPnv/dT1ZuDP8LJKojZN5XDpggvraXu75h0hsN2L3HJnRbL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3EXBuq5WPBJZYSGs6do+xnoHz5H6mksCZ0Ucvjf BwAYtZdUg1Gj8kSR951cJzrho+vRkpesaJxHIMU+eKiFqFzZPd8KvDtX/5ijUFapw+HChniQMOrm xL4g64cXAZfXCEgAM80e4VzQ6WzfdUy+lXdJB+GmVX9hx1K4uCSCUOZMgmjhvHOHDv/Y68mAHfeD 8QSKsavdHgfyqtsMT2r96hgiVcMybz+Rba+WvHzJSIaeBLkUnoz4NnjXR0Ey0YHm5j7Z+JBhJHQi tt4cTDbmCY/SLxw9e2hc2N6ES8HgC7iHGT5fok97RIpLVlbEEVD2STpq2ZasoQJc9DYGbBVIdfIJ 6S3h2lHfwhnq9mD5";
            $decyptedData = Mage::helper('core')->decrypt(base64_decode($encryptedData));
            print_r($decyptedData);
        } 
      public function getProductChildren(Mage_Catalog_Model_Product $product)
    {
        if (isset($this->_children[$product->getId()])) {
            return $this->_children[$product->getId()];
        }
        $attributesToSelect = array(
            'price',
            'special_price',
            'special_from_date',
            'special_to_date');
        $configurableProductsData = $product->getConfigurableProductsData();
        if (!is_array($configurableProductsData)) {
            $childrenIds = Mage::getModel('catalog/product_type_configurable')->getChildrenIds($product->getId());
        }
        else {
            $childrenIds = array(0 => array());
            foreach ($configurableProductsData as $key => $value) {
                $childrenIds[0][$key] = $key;
            }
        }
        if (empty($childrenIds) || empty($childrenIds[0])) {
            $children = null;
        }
        else {
            $children = Mage::getModel('catalog/product')->getCollection()
                ->addIdFilter($childrenIds)
                ->addAttributeToSelect($attributesToSelect);
        }
        return $this->_children[$product->getId()] = $children;
    }
        protected function getAttributesOption($attributId) {
            $attributeObject=Mage::getModel('eav/config')->getAttribute('catalog_product')->load($attributId);
            $options = $attributeObject->setStoreId(Mage::app()->getStore()->getId())->getSource()->getAllOptions(false);
            return $options;
        }
        
        public function getConfigurableAttributesArray(Mage_Catalog_Model_Product $product)
        {
            $attributes = $product->getTypeInstance()->getConfigurableAttributes($product);
            $attributesArray = array();
            foreach ($attributes as $attribute) {
                $attributeObject = Mage::getModel('eav/entity_attribute')->load($attribute->getAttributeId());
                $attributesArray[] = $attributeObject->getAttributeCode();
            }
            return $attributesArray;
        }
        public function indexAction(){

           $_product = Mage::getModel('catalog/product')->load("6475");
           
       //get associative (child) products
                    $childProducts = Mage::getModel('catalog/product_type_configurable')->getUsedProducts(null,$_product);
                    $childPriceLowest = "";    
                    $childPriceHighest = "";       
                    foreach($childProducts as $child){
                        $_child = Mage::getModel('catalog/product')->load($child->getId());
                        $childData[] = $_child->getData();

                    }
                    $price_array = array($childPriceLowest,$childPriceHighest); // array containing required values
      
                echo "<pre/>";
               
                print_r($childData);
              //print_r($childProducts);
                echo "<pre/>";
            }
            public function indexsAction($attributeSetId = 43, $select = array("common_color","common_clothing_size"),$simpleProductArr=array("7679","7678")){
                $AttributeCode   =array();
                $attributes = Mage::getModel('catalog/product_attribute_api')->items($attributeSetId);
                foreach($attributes as $_attribute)
                {
                    if($_attribute['scope'] == 'global' && $_attribute['type'] == 'select')
                    {
                        $super_attribute = Mage::getModel('eav/entity_attribute')->loadByCode('catalog_product',$_attribute['code']);
                        if($super_attribute->getIsConfigurable() == 1)
                        {
                            $AttributeCodeData[] = $super_attribute->getData();
                        }
                    }
                }
                $simpleProducts = Mage::getResourceModel('catalog/product_collection')
                ->addIdFilter($simpleProductArr);
                foreach ($select as $val){
                    $simpleProducts -> addAttributeToSelect($val);
                }
                foreach ($AttributeCodeData as  $configurableAtt){
                    foreach ($select as $attribute_code ){
                        if($configurableAtt['attribute_code'] == $attribute_code ){
                            foreach ($simpleProducts as $simple){
                                $productinfo = array(
                                    'label' => $simple->getAttributeText($configurableAtt['attribute_code']),
                                    'attribute_id' => $configurableAtt['attribute_id'],
                                    'value_index' => (int) $simple->getData($attribute_code),
                                    'is_percent' => 0,
                                    'pricing_value' => $simple->getPrice()
                                );
                                $values[$attribute_code][]= $productinfo;
                                $configurableProductsData[$simple->getId()][] = $productinfo;
                            }
                            
                            $configurableAttributesData[] = array(
                                'label'          => $configurableAtt['frontend_label'],
                                'position'       => $configurableAtt['position'],
                                'values'         => $values[$attribute_code]?$values[$attribute_code]:array(),
                                'attribute_id'   => $configurableAtt['attribute_id'],
                                'attribute_code' =>  $configurableAtt['attribute_code'],
                                'frontend_label' =>$configurableAtt['frontend_label'],
                            );
                        }
                    }
                }
                $configurableKey['configurable_attributes_data'] = $configurableAttributesData;
                $configurableKey['configurable_products_data']  = $configurableProductsData;
                echo "<pre/>";
                var_dump($configurableKey);
               // return $configurableKey;//返回用户所绑定的属性
            }
            public function aAction() {
                $asd = Mage::getModel("autocoupon/couponlog");
               $asd->setCouponId("23")
                ->setEmail("649319205@qq.com")
                ->setEventsCode("asdsad")
                ->save();
              }
        
         public function conAction(){
             try {
                  
                 $login = array(
                     'username' => 'wtj5200123@gmail.com',
                     'password' => '123456',
                 );
                 //180.150.141.217
                 $client = new SoapClient('http://47.88.0.58/magento/api/v2_soap/?wsdl=1');
                 // $session  = $client ->login('tian','wangzai');
             
                 $sessionId = $client->login((object)array('username' => 'tian', 'apiKey' => 'wangzai'));
             
$simple =    <<<XML
<?xml version='1.0' encoding='utf-8'?>
<request>
    <simple>
        <set_id>43</set_id>
        <name>test_product11</name>
        <vendor_sku>fox</vendor_sku>
        <categories>
            <categorie>2</categorie>
        </categories>
        <websites>
            <website>1</website>
        </websites>
        <description>description</description>
        <short_description>Product tianjun123</short_description>
        <weight>10</weight>
        <visibility>4</visibility>
        <tax_class_id>0</tax_class_id>
        <meta_title>Product meta title</meta_title>
        <meta_keyword>Product meta keyword</meta_keyword>
        <meta_description>Product meta description</meta_description>
        <common_brand >nike</common_brand >
        <common_package_length>23</common_package_length>
        <common_package_width>23</common_package_width>
        <common_package_height>23</common_package_height>
        <common_shipping_type>14</common_shipping_type>
        <common_shipping_method>19</common_shipping_method>
        <common_dimensional_weight>0</common_dimensional_weight>
        <common_supply_price>30</common_supply_price>
        <common_product_name>Rich Long Jewelry Sets</common_product_name>
        <stock_data>
        <use_config_manage_stock>1</use_config_manage_stock>
        <manage_stock>1</manage_stock>
        <min_sale_qty>1</min_sale_qty>
        <max_sale_qty>2</max_sale_qty>
        <is_in_stock>1</is_in_stock>
        <qty>2</qty>
        </stock_data>
     </simple>
     <simple>
        <set_id>43</set_id>
        <vendor_sku>oop</vendor_sku>
        <name>Product name</name>
        <description>tianjun123</description>
        <short_description>Product tianjun123</short_description>
        <weight>10</weight>
        <visibility>4</visibility>
        <tax_class_id>0</tax_class_id>
        <meta_title>Product meta title</meta_title>
        <meta_keyword>Product meta keyword</meta_keyword>
        <meta_description>Product meta description</meta_description>
        <common_brand >nike</common_brand >
        <common_package_length>23</common_package_length>
        <common_package_width>23</common_package_width>
        <common_package_height>23</common_package_height>
        <common_shipping_type>14</common_shipping_type>
        <common_shipping_method>19</common_shipping_method>
        <common_dimensional_weight>0</common_dimensional_weight>
        <common_supply_price>30</common_supply_price>
        <common_product_name>Rich Long Jewelry Sets</common_product_name>
        <stock_data>
       		<use_config_manage_stock>1</use_config_manage_stock>
            <manage_stock>1</manage_stock>
            <min_sale_qty>1</min_sale_qty>
            <max_sale_qty>2</max_sale_qty>
            <is_in_stock>1</is_in_stock>
            <qty>12</qty>
        </stock_data>
    </simple>
    <simple>
        <set_id>43</set_id>
        <vendor_sku>ppo</vendor_sku>
        <name>asd大声道</name>
        <description>tianjun123</description>
        <short_description>Product tianjun123</short_description>
        <weight>10</weight>
        <visibility>4</visibility>
        <tax_class_id>0</tax_class_id>
        <meta_title>Product meta title</meta_title>
        <meta_keyword>Product meta keyword</meta_keyword>
        <meta_description>Product meta description</meta_description>
        <common_brand >nike</common_brand >
        <common_package_length>23</common_package_length>
        <common_package_width>23</common_package_width>
        <common_package_height>23</common_package_height>
        <common_shipping_type>14</common_shipping_type>
        <common_shipping_method>19</common_shipping_method>
        <common_dimensional_weight>0</common_dimensional_weight>
        <common_supply_price>30</common_supply_price>
        <common_product_name>Rich Long Jewelry Sets</common_product_name>
        <stock_data>
       		<use_config_manage_stock>1</use_config_manage_stock>
            <manage_stock>1</manage_stock>
            <min_sale_qty>1</min_sale_qty>
            <max_sale_qty>2</max_sale_qty>
            <is_in_stock>1</is_in_stock>
            <qty>12</qty>
        </stock_data>
    </simple>
</request>
XML;
                 $login = json_encode($login);
              			$result = $client->productApiuploadSimple((object)array('sessionId'=>$sessionId->result,'productData'=>$simple,'login'=>$login));
              		 echo "<pre/>";
              		 var_dump($result);
              		 echo "<pre/>";
             
             
             
             } catch (Exception $e) {
                 echo "<pre/>";
                 var_dump($e->getMessage());
                 echo "<pre/>";
             }
              
         }
         public function createCodeAction()
         {
             // Get the rule in question
             $rule = Mage::getModel('salesrule/rule')->load(2); //21 = ID of coupon in question
         
             // Define a coupon code generator model instance
             // Look at Mage_SalesRule_Model_Coupon_Massgenerator for options
             
             $generator = Mage::getModel('salesrule/coupon_massgenerator');
         
             $parameters = array(
                 'count'=>5,
                 'format'=>'alphanumeric',
                 'dash_every_x_characters'=>4,
                 'prefix'=>'ABCD-EFGH-',
                 'suffix'=>'-WXYZ',
                 'length'=>8
             );
         
             if( !empty($parameters['format']) ){
                 switch( strtolower($parameters['format']) ){
                     case 'alphanumeric':
                     case 'alphanum':
                         $generator->setFormat( Mage_SalesRule_Helper_Coupon::COUPON_FORMAT_ALPHANUMERIC );
                         break;
                     case 'alphabetical':
                     case 'alpha':
                         $generator->setFormat( Mage_SalesRule_Helper_Coupon::COUPON_FORMAT_ALPHABETICAL );
                         break;
                     case 'numeric':
                     case 'num':
                         $generator->setFormat( Mage_SalesRule_Helper_Coupon::COUPON_FORMAT_NUMERIC );
                         break;
                 }
             }
         
             $generator->setDash( !empty($parameters['dash_every_x_characters'])? (int) $parameters['dash_every_x_characters'] : 0);
             $generator->setLength( !empty($parameters['length'])? (int) $parameters['length'] : 6);
             $generator->setPrefix( !empty($parameters['prefix'])? $parameters['prefix'] : '');
             $generator->setSuffix( !empty($parameters['suffix'])? $parameters['suffix'] : '');
         
             // Set the generator, and coupon type so it's able to generate
             $rule->setCouponCodeGenerator($generator);
             $rule->setCouponType( Mage_SalesRule_Model_Rule::COUPON_TYPE_AUTO );
         
             // Get as many coupons as you required
             $count = !empty($parameters['count'])? (int) $parameters['count'] : 1;
             $codes = array();
             for( $i = 0; $i < 1; $i++ ){
                 $coupon = $rule->acquireCoupon();
                 $coupon
                 ->setType(Mage_SalesRule_Helper_Coupon::COUPON_TYPE_SPECIFIC_AUTOGENERATED)
                  ->save();
                 echo "<pre/>";
                  print_r($coupon);
                  echo "<pre/>";
                 $code = $coupon->getCode();
                 $codes[] = $code;
             }
            
         }
         public function showtAction(){
         
          // Get the rule in question
        $rule = Mage::getModel('salesrule/rule')->load($rule_id); //21 = ID of coupon in question
         
        // Define a coupon code generator model instance
        // Look at Mage_SalesRule_Model_Coupon_Massgenerator for options
         
        $generator = Mage::getModel('salesrule/coupon_massgenerator');
        if(!is_numeric($count)){
            $count = 1;
         }
        $parameters = array(
            'count'=>$count,
            'format'=>$format,
            'dash_every_x_characters'=>$dash_every_x_characters,
            'prefix'=>$prefix,
            'suffix'=>$suffix,
            'length'=>$length,
        );
         
        if( !empty($parameters['format']) ){
            switch( strtolower($parameters['format']) ){
                case 'alphanumeric':
                case 'alphanum':
                    $generator->setFormat( Mage_SalesRule_Helper_Coupon::COUPON_FORMAT_ALPHANUMERIC );
                    break;
                case 'alphabetical':
                case 'alpha':
                    $generator->setFormat( Mage_SalesRule_Helper_Coupon::COUPON_FORMAT_ALPHABETICAL );
                    break;
                case 'numeric':
                case 'num':
                    $generator->setFormat( Mage_SalesRule_Helper_Coupon::COUPON_FORMAT_NUMERIC );
                    break;
            }
        }     
        $generator->setDash( !empty($parameters['dash_every_x_characters'])? (int) $parameters['dash_every_x_characters'] : 0);
        $generator->setLength( !empty($parameters['length'])? (int) $parameters['length'] : 6);
        $generator->setPrefix( !empty($parameters['prefix'])? $parameters['prefix'] : '');
        $generator->setSuffix( !empty($parameters['suffix'])? $parameters['suffix'] : '');
         
        // Set the generator, and coupon type so it's able to generate
        $rule->setCouponCodeGenerator($generator);
        $rule->setCouponType( Mage_SalesRule_Model_Rule::COUPON_TYPE_AUTO );
         
        // Get as many coupons as you required
        $count = !empty($parameters['count'])? (int) $parameters['count'] : 1;
        $codes = array();
        for( $i = 0; $i < $count; $i++ ){
            $coupon = $rule->acquireCoupon();
            $coupon
            ->setType(Mage_SalesRule_Helper_Coupon::COUPON_TYPE_SPECIFIC_AUTOGENERATED)
            ->save();
            $code = $coupon->getCode();
            $codes['code'][] = $code;
        }
           $codes['description']= $rule->getDescription();
           $codes['name']= $rule->getName();
           Mage::log($codes);
           print_r($codes);
    
             
             
         }
    }